package cn.kgc.controller;

import cn.kgc.commons.annotation.MyCacheable;
import cn.kgc.commons.exception.HttpException;
import cn.kgc.commons.vo.Result;
import cn.kgc.entity.PmsCategoryBrandRelation;
import cn.kgc.service.PmsCategoryBrandRelationService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import cn.kgc.entity.PmsCategory;
import cn.kgc.dto.PmsCategoryAddDTO;
import cn.kgc.dto.PmsCategoryUpdateDTO;
import cn.kgc.service.PmsCategoryService;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import jodd.util.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;

import com.baomidou.mybatisplus.core.metadata.IPage;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

/**
 * 商品三级分类(PmsCategory)表控制层
 *
 * @author makejava
 * @since 2022-11-27 10:34:56
 */
@RestController
@RequestMapping("pms/category")
@Api
@Validated
@Slf4j
public class PmsCategoryController {
    /**
     * 服务对象
     */
    @Resource
    private PmsCategoryService pmsCategoryService;

    @Resource
    private PmsCategoryBrandRelationService pmsCategoryBrandRelationService;


    @GetMapping("/list/menu")
    @CrossOrigin
    @ApiOperation(value="首页商品的分类的菜单",
            httpMethod = "GET",produces = "application/json",response = Result.class)
    @Cacheable(value = "pmsCategory",key = "#root.method.name")

    public List<PmsCategory>listPmsCategoryMenu(){

        //从数据库中查找
        List<PmsCategory> pmsCategoryList = pmsCategoryService.list();

        log.info("数据库中商品分类信息:{}",pmsCategoryList);

        List<PmsCategory> result=new ArrayList<>(); //最终的返回结果

        //组装费雷信息
        pmsCategoryList.forEach(pmsCategory->{
            if(pmsCategory.getCatLevel()==1){  //获得商品分类的一级分类

                getPmsChildPmsCategory(pmsCategory,pmsCategoryList);

                result.add(pmsCategory);

            }
        });

        log.info("查询商品分类菜单:{}",result);

        //将商品的result集合，按照sort值排序
       result.sort(Comparator.comparingInt(PmsCategory::getSort));
        return result;
    }




    /**
     * 从pmsCategories中查找子分类
     * @param pmsCategory
     * @param pmsCategories
     */
    public void  getPmsChildPmsCategory(PmsCategory pmsCategory,List<PmsCategory> pmsCategories){

        pmsCategories.forEach(pmsCategory1->{ //遍历pmsCategories元素
            //查找pmsCategory的子分类
            if (pmsCategory.getId()==pmsCategory1.getParentCid()){

                //查找pmsCategory1的子分类
                getPmsChildPmsCategory(pmsCategory1,pmsCategories);
                //向pmsCategory子分类的集合中添加查找到子分类pmsCategory1
                pmsCategory.getPmsCategoryList().add(pmsCategory1);

                pmsCategory.getPmsCategoryList().sort(Comparator.comparingInt(PmsCategory::getSort));
            }

        });

    }






    /**
     * 分页查询所有数据
     *
     * @param current 分页对象
     * @return 所有数据
     */
    @GetMapping("/list/page")
    @ApiOperation(value = "分页查询所有数据", produces = "application/json;charset=utf-8",
            httpMethod = "GET", response = Result.class)
    @ApiImplicitParam(name = "current", value = "当前页", paramType = "query", dataType = "int")
    @CrossOrigin
    public IPage<PmsCategory> selectAll(@RequestParam(defaultValue = "1") int current,
                                        @RequestParam(defaultValue = "5") int pageSize) {
        IPage<PmsCategory> page = new Page(current, pageSize);

        return pmsCategoryService.page(page);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    @CrossOrigin
    @ApiOperation(value = "通过主键查询单条数据", produces = "application/json;charset=utf-8",
            httpMethod = "GET", response = Result.class)
    @ApiImplicitParam(name = "id", value = "主键", paramType = "path", dataType = "int")
//   @Cacheable(value="pmscategory",key="#id")
  @MyCacheable(cacheName = "pmscategory",cacheKey = "#id",time = 1,timeUnit = TimeUnit.MINUTES)
    public PmsCategory selectOne(@PathVariable Serializable id) {
        return this.pmsCategoryService.getById(id);
    }

    /**
     * 新增数据
     *
     * @param pmsCategoryDTO 实体对象
     * @return 新增结果
     */
    @PostMapping("/insert")
    @ApiOperation(value = "新增", produces = "application/json;charset=utf-8",
            httpMethod = "POST", response = Result.class)
    @CrossOrigin
    @CacheEvict(value="pmscategory",key="listPmsCategoryMenu")
    public boolean insert(@RequestBody PmsCategoryAddDTO pmsCategoryDTO) {
        PmsCategory pmsCategory = new PmsCategory();
        BeanUtils.copyProperties(pmsCategoryDTO, pmsCategory);
        return this.pmsCategoryService.save(pmsCategory);
    }

    /**
     * 修改数据
     *
     * @param pmsCategoryDTO 实体对象
     * @return 修改结果
     */
    @PostMapping("/update")
    @ApiOperation(value = "修改信息", produces = "application/json;charset=utf-8",
            httpMethod = "POST", response = Result.class)
    @CrossOrigin

    //更新数据时候，删除多个缓存
    @Caching(evict = {
            @CacheEvict(value = "pmscategory", key = "'selectOne'+#pmsCategoryDTO.id"),
           @CacheEvict(value="pmscategory",key="listPmsCategoryMenu")
    })
//    @CacheEvict(value="pmscategory",key="'selectOne'+#pmsCategoryDTO.id")
    public boolean update(@RequestBody PmsCategoryUpdateDTO pmsCategoryDTO) {
        PmsCategory pmsCategory = this.pmsCategoryService.getById(pmsCategoryDTO.getId());
        BeanUtils.copyProperties(pmsCategoryDTO, pmsCategory);
        return this.pmsCategoryService.updateById(pmsCategory);
    }



    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除结果
     */
    @DeleteMapping("/del/{id}")
    @ApiOperation(value = "根据主键删除信息", produces = "application/json;charset=utf-8",
            httpMethod = "DELETE", response = Result.class)
    @ApiImplicitParam(name = "id", value = "主键", paramType = "path", dataType = "int")
    @CrossOrigin
    @Caching(evict = {
            @CacheEvict(value = "pmscategory", key = "'selectOne'+#id"),
            @CacheEvict(value="pmscategory",key="'listPmsCategoryMenu'")
    })
    public boolean delete(@PathVariable Long id) { //, HttpServletRequest request)
        LambdaQueryWrapper<PmsCategoryBrandRelation>lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PmsCategoryBrandRelation::getCatelogId,id);
        List<PmsCategoryBrandRelation> list =
                pmsCategoryBrandRelationService.list(lambdaQueryWrapper);
        log.info("删除的分类与品牌关联的数据：{}",list);
        //如果关联为空，分类没有与任何品牌挂钩，可以删除
        if (CollectionUtils.isEmpty(list)){
            log.info("删除分类信息:{}",id);

            return this.pmsCategoryService.removeById(id);
//            if (result){
//                return Result.ok(result,request.getRequestURL().toString());
//            }
        }
        throw new HttpException(20001,500);

    }
}
